<template>
    <div class="registerMain">
      <div class="registerBox">
        <div class="header-text"><p>注册</p></div>
        <a-form
          ref="formRef"
          :model="formState"
          :rules="rules"
          v-bind="layout"
          class="login-form"
          @finish="handleFinish"
          @validate="handleValidate"
          @finishFailed="handleFinishFailed"
    >
      <a-form-item
        label="手机号"
        name="username"
        :rules="[{ required: true, message: '请输入正确的手机号',pattern:/^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/ }]"
      >
        <a-input v-model:value="formState.username">
        </a-input>
      </a-form-item>
  
      <a-form-item has-feedback label="密码" name="pass">
        <a-input v-model:value="formState.pass" type="password" autocomplete="off" />
      </a-form-item>
      <a-form-item has-feedback label="重复密码" name="checkPass">
        <a-input v-model:value="formState.checkPass" type="password" autocomplete="off" />
      </a-form-item>
      <div class="captchaBox">
        <a-form-item has-feedback label="验证码" name="captcha" :labelCol="itemLayout">
          <a-input v-model:value="formState.captcha"></a-input>
        </a-form-item>
        <div class="login-code">
          <img :src="codeUrl" class="login-code-img" @click="getCode" />
        </div>
      </div>
      <div class="existsAccount" @click="goLogin">
        已有账号? 前往登录
      </div>
      
      <a-form-item :wrapper-col="{ span: 14, offset: 6 }">
        <a-button type="primary" html-type="submit" :disabled="disabled">Submit</a-button>
        <a-button style="margin-left: 10px" @click="resetForm">Reset</a-button>
      </a-form-item>
  
    </a-form>
      </div>
    </div>
    
    
</template>
<script lang="ts" setup>
import { reactive, computed, ref,onMounted } from 'vue';
import type { Rule } from 'ant-design-vue/es/form';
import type { FormInstance } from 'ant-design-vue';
import  { message } from 'ant-design-vue';
import { getCodeImg,register } from '@/api/login';
import { LoginData } from '@/api/types';
import { useRouter } from 'vue-router';

const router = useRouter();

//验证码
const codeUrl = ref('');

const captchaEnabled = ref(true);

const loginForm = ref<LoginData>({
  tenantId: '000000',
  username: 'admin',
  password: 'admin123',
  userType: 'front_user',
  rememberMe: false,
  code: '',
  uuid: '',
  clientId:import.meta.env.VITE_APP_CLIENT_ID
} as LoginData);

const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  console.log(data);
  
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
}

const goLogin=()=>{
  router.replace('/login')
}

interface FormState {
  username: string;
  pass: string;
  checkPass: string;
  captcha: string;
}

const formState = reactive<FormState>({
  username: '',
  pass: '',
  checkPass: '',
  captcha: ''
});
//提交按钮禁用
const disabled = computed(() => {
  return !(formState.username&& formState.pass&& formState.checkPass&& formState.captcha);
});

const formRef = ref<FormInstance>();

//验证提示
//validateFields触发表单验证
const validateName = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('请输入手机号');
  } else {
    if (formState.username !== '') {
      formRef.value.validateFields('name');
    }
    return Promise.resolve();
  }
};
const validatePass = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('请输入密码');
  } else {
    if (formState.checkPass !== '') {
      formRef.value.validateFields('checkPass');
    }
    return Promise.resolve();
  }
};
const validatePass2 = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('请重新输入密码');
  } else if (value !== formState.pass) {
    return Promise.reject("两个输入不匹配!");
  } else {
    return Promise.resolve();
  }
};

// const checkCaptcha = async (_rule: Rule, value: string) => {
//   console.log(1);
  
//   if (value === '') {
//     return Promise.reject('请输入验证码');
//   } else {
//     if (formState.username !== '') {
//       formRef.value.validateFields('captcha');
//     }
//     return Promise.resolve();
//   }
// };

//required: true控制红色星号样式
const rules: Record<string, Rule[]> = {
  name: [{ required: true, validator: validateName, trigger: 'change' }],
  pass: [{ required: true, validator: validatePass, trigger: 'change' }],
  checkPass: [{ required: true,validator: validatePass2, trigger: 'change' }],
  // captcha: [{ required: true,validator: checkCaptcha, trigger: 'change' }]
  captcha: [{ required: true, trigger: 'change' }]
};
//input框样式
const layout = {
  labelCol: {span: 7},
  wrapperCol: { span: 18 }
};

const itemLayout={
  span:10
}
// 回调函数
const handleFinish = async (values: FormState) => {
  loginForm.value.username=values.username
  loginForm.value.password=values.pass
  loginForm.value.code=values.captcha
  
  try{
    const res=await register(loginForm.value)
    if(res.code===200){
    message.success('注册成功，即将跳转登录！');
    setTimeout(()=>{
      router.replace('/login')
    },2500)
  }
  }catch(err:any){
    message.warning(err.message);
  }

};
const handleFinishFailed = errors => {
  console.log(errors);
};
const resetForm = () => {
  formRef.value.resetFields();
};
const handleValidate = (...args) => {
  console.log(args);
};

onMounted(() => {
  getCode();
});
</script>
<style scoped lang="scss">
:deep(.ant-input-password) {
  padding: 0;
}

:deep(.ant-input-password-icon) {
  margin-right: 0;
  height: 100%;
  display: flex;
  align-items: center;
}

:deep(.ant-input-affix-wrapper) {
  padding: 0 11px;
}

:deep(.ant-input-affix-wrapper-focused),
:deep(.ant-input-affix-wrapper:focus) {
  padding: 0 11px;
}

:deep(.ant-input-focused),
:deep(.ant-input:focus) {
  outline: none;
  box-shadow: none !important;
}

:deep(.ant-input-affix-wrapper-focused .ant-input) {
  width: 100%;
  outline: none;
}
  .registerMain{
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    
    .registerBox{
      width: 480px;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      padding: 74px 70px;
      background: rgba( 77, 156, 221, 0.5 );
      box-shadow: 0 8px 32px 0 rgba( 31, 38, 135, 0.37 );
      backdrop-filter: blur( 5px );
      -webkit-backdrop-filter: blur( 5px );
      border-radius: 10px;
      border: 1px solid rgba( 255, 255, 255, 0.18 );
      .formBox{
        width: 450px;
        display: flex;
        align-items: center;
        flex-direction: column;
      }
      .header-text{
        color: azure;
        font-size:2rem;
        font-family: "宋体";
      }
    }
  
    .form-item-box{
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  
  .login-code {
    width: 33%;
    height: 40px;
    float: right;
  
    img {
      width: 87.25px;
      height: 100%;
      cursor: pointer;
      vertical-align: middle;
    }
  }

  .register-code-img {
    height: 40px;
    padding-left: 12px;
  }

  .captchaBox{
    display: flex;
    &>div:nth-child(2){
      padding-left: 20px;
    }
  }

  .existsAccount{
    padding-left: 20px;
    color: azure;
    cursor: pointer;
    padding-bottom: 10px;
  }
  
  #components-form-demo-normal-login .login-form {
    max-width: 500px;
  }
  #components-form-demo-normal-login .login-form-forgot {
    float: right;
  }
  #components-form-demo-normal-login .login-form-button {
    width: 100%;
  }
  </style>
  